package com.personal.dao.extractor;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import com.personal.dao.configuration.Configuration;
import com.personal.dao.exception.NoDefaultContructorException;
import com.personal.dao.handler.HandlerUtil;
import com.personal.dao.metadata.DataBaseTableMetadata;
import com.personal.dao.reflection.MetaClass;

public class BaseModelResultSetExtractor<T> implements ResultSetExtractor<T>
{

    private DataBaseTableMetadata<T> metadata;

    public BaseModelResultSetExtractor(DataBaseTableMetadata<T> metadata)
    {
        super();
        this.metadata = metadata;
    }

    @Override
    public T extractData(ResultSet rs) throws SQLException, DataAccessException
    {
        if (rs.next())
        {
            MetaClass metaClass = Configuration.getInstance().newMetaClass(metadata.getC());
            if (!metaClass.hasDefaultConstructor())
            {
                throw new NoDefaultContructorException("请给" + metadata.getC() + "提供默认的构造器！");
            }
            // 获取元数据
            ResultSetMetaData sqlmetaData = rs.getMetaData();
            // 生成对象
            T result = Configuration.getInstance().getObjectFactory().create(metadata.getC());
            HandlerUtil.setResultData2MetaObject(rs, sqlmetaData, metadata, result);
            return result;
        }
        return null;
    }

}
